package com.tianxiao.faas.application.web.corner;

import com.google.common.collect.Lists;
import com.tianxiao.faas.api.param.corner.*;
import com.tianxiao.faas.application.aop.AuthenticationContext;
import com.tianxiao.faas.application.aop.AuthenticationContextHolder;
import com.tianxiao.faas.biz.service.corner.ShopService;
import com.tianxiao.faas.common.access.Access;
import com.tianxiao.faas.common.result.Result;
import com.tianxiao.faas.mapper.model.ShopModel;
import com.tianxiao.faas.mapper.model.TagsModel;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/app/admin/shop/")
public class ShopAdminController {
    @Resource
    private ShopService shopService;

    @RequestMapping(value = "/list")
    @Access(access = {"admin"})
    public Result<List<ShopResult>> list(@RequestBody ShopPageParam param) {
        return shopService.page(param);
    }

    @RequestMapping(value = "/save")
    @Access(access = {"admin"}, action = "店铺创建")
    public Result<Boolean> create(@RequestBody ShopInfoAdminParam param) {
        shopService.saveShopInfo(param);
        return Result.builder().data(true).success(true);
    }




    @RequestMapping(value = "/getById")
    @Access(access = {"admin"})
    public Result<ShopInfoResult> getById(@RequestBody ShopPageParam param) {
        if (param.getShopId() == null) {
            return Result.builder().data(null).success(true);
        }
        ShopModel shop = shopService.getById(param.getShopId());
        if (shop == null) {
            return Result.builder().data(null).success(true);
        }
        ShopInfoResult shopInfoParam = shopService.getShopInfoParam(shop, param.getLatitude(), param.getLongitude());
        Long shopId = shop.getId();
        Map<Long, List<TagsModel>> longListMap =
                shopService.getLongListMap(Lists.newArrayList(shopId));
        shopInfoParam.setTags(shopService.buildTagEntity(longListMap, shopId));
        shopInfoParam.setProductResults(shopService.getProductsByShopId(shopId));
        return Result.builder().data(shopInfoParam).success(true);
    }

    @RequestMapping(value = "/goods/save")
    @Access(access = {"admin"}, action = "店铺创建")
    public Result<Boolean> saveGoods(@RequestBody ProductResult param) {
        ShopModel byUserId = shopService.getById(param.getShopId());
        shopService.saveProducts(Lists.newArrayList(param), byUserId);
        return Result.builder().data(true).success(true);
    }

    @RequestMapping(value = "/delete")
    @Access(access = {"admin"}, action = "店铺删除")
    public Result<Boolean> delete(Long id) {
        shopService.deleteShop(id);
        return Result.builder().data(true).success(true);
    }
}
